import {
  isURL
} from '@/utils/validate'
/*
 * 设置setLocalStorage
 * */
export function setLocalStorage(key, value) {
  window.localStorage.setItem(key, window.JSON.stringify(value));
}
/*
 * 获取getLocalStorage
 * */
export function getLocalStorage(key) {
  return window.JSON.parse(window.localStorage.getItem(key) || "[]");
}
/*
 * 设置setSessionStorage
 * */
export function setSessionStorage(key, value) {
  window.sessionStorage.setItem(key, window.JSON.stringify(value));
}
/*
 * 获取getSessionStorage
 * */
export function getSessionStorage(key) {
  return window.JSON.parse(window.sessionStorage.getItem(key) || "[]");
}

export function generateChildRouters(data) {
  const routers = [];
  for (let item of data) {
    let component = "";
    if (item.component.indexOf("layouts") >= 0) {
      component = "components/" + item.component;
    } else {
      component = "views/" + item.component;
    }

    // eslint-disable-next-line
    let URL = (item.meta.url || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量
    if (isURL(URL)) {
      item.meta.url = URL;
    }

    let componentPath = resolve => require(['@/views/' + component + '.vue'], resolve)

    let menu = {
      path: item.path,
      name: item.name,
      redirect: item.redirect,
      component: componentPath,
      //component: resolve => require(['@/' + component+'.vue'], resolve),
      hidden: item.hidden == 1 ? true : false,
      //component:()=> import(`@/views/${item.component}.vue`),
      meta: {
        title: item.meta.title,
        // icon: item.meta.icon,
        url: item.meta.url,
        permissionList: item.meta.permissionList,
        keepAlive: item.meta.keepAlive == 1 ? true : false,
        /*update_begin author:wuxianquan date:20190908 for:赋值 */
        internalOrExternal: item.meta.internalOrExternal,
        /*update_end author:wuxianquan date:20190908 for:赋值 */
        componentName: item.name
      }
    }
    if (item.alwaysShow) {
      menu.alwaysShow = true;
      menu.redirect = menu.path;
    }
    if (item.children && item.children.length > 0) {
      menu.children = [...generateChildRouters(item.children)];
    }
    //--update-begin----author:scott---date:20190320------for:根据后台菜单配置，判断是否路由菜单字段，动态选择是否生成路由（为了支持参数URL菜单）------
    //判断是否生成路由
    if (item.route && item.route === '0') {
      //console.log(' 不生成路由 item.route：  '+item.route);
      //console.log(' 不生成路由 item.path：  '+item.path);
    } else {
      routers.push(menu);
    }
    //--update-end----author:scott---date:20190320------for:根据后台菜单配置，判断是否路由菜单字段，动态选择是否生成路由（为了支持参数URL菜单）------
  }
  console.log('routers:', routers)
  return routers
}

/**
 * 
 * @param {*} that vm实例
 * @param {*} error 错误数据
 */
export function dealCatchMessage(that,error) {
  if (typeof error == 'object' && error.code == 201) {
    that.$message.error(error.msg);
  } else that.$message.error('操作失败');
  that.$loading.hide()
}